

<template>
    <RouterView v-if="isRouteActive" />
    <Tabbar v-if="isShowNav"></Tabbar>
</template>

<script setup>
import Tabbar from '@/components/Tabbar.vue'
import { ref, watch, onMounted, provide, nextTick, onUpdated, onBeforeMount, onBeforeUpdate, onBeforeUnmount, onUnmounted } from 'vue'
import { RouterView, useRoute } from 'vue-router'
import { useCartStore } from './stores/cart.js'
import { useAddressStore } from './stores/address.js'
import { useUserStore } from '@/stores/user.js'
import { getToken } from '@/utils/token.js'
const store = useCartStore()
const addressStore = useAddressStore()
const userStore = useUserStore()
const route = useRoute()
const isShowNav = ref(false)

watch(route, newVal => {
    isShowNav.value = newVal.meta.isShowNav
})


onBeforeMount(() => {
    console.log('onBeforeMount');

})

onMounted(async () => {
    console.log('onMounted');
    //判断是否有token
    if (getToken()) {
        //判断token是否过期或被修改，因为获取购物车数据接口必须携带正确token才能获取到数据，
        //如果token过期或被修改，后端返回的状态被相应拦截器拦截，清除购物车仓库数据
        let userInfo = JSON.parse(decodeURI(atob(localStorage.getItem('info'))));
        userStore.getUserInfo(userInfo.name, userInfo.pwd)
        store.getCart()
        addressStore.getAddressInfo()
    } else {
        //这里其实不用做重置仓库的操作了，若token被修改，响应拦截器中直接把旧token删除，
        //等刷新页面仓库数据自动就消失了，走到这重新判断没有token也不会重新请求数据放到仓库中
    }
})

onBeforeUpdate(() => {
    console.log('onBeforeUpdate');
})

//v-if会触发onUpdated
onUpdated(() => {
    //没判断就请求接口，结果被响应拦截器拦截去登录页
    //这里必须包裹判断一下是否有token，这个接口是需要token的，
    //刷新页面就会调用这个onUpdated钩子，如果没token就请求接口，响应拦截器就拦截下来了让我去登录页
    if (getToken()) {
        let userInfo = JSON.parse(decodeURI(atob(localStorage.getItem('info'))));
        userStore.getUserInfo(userInfo.name, userInfo.pwd)
        store.getCart()
        addressStore.getAddressInfo()
    }
})

onBeforeUnmount(() => {
    console.log('onBeforeUnmount');
})
onUnmounted(() => {
    console.log('onUnmounted');
})

const isRouteActive = ref(true);
const fn = () => {
    isRouteActive.value = false;
    nextTick(() => {
        isRouteActive.value = true;
    })
}

provide('reload', fn)


</script>


<style  scoped></style>
